package com.mlog.njyjy.ndop.share.sql.support;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.jfinal.plugin.activerecord.Model;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * .
 * </p>
 *
 * @author <a href="mailto:yingxiufeng@mlogcn.com">alex</a>
 * @version v1.0, 2020/8/11
 */
public final class SqlHelper {

    public static <T> T pureAttrs2Fields(T entity, Class<T> tblClass) {
        if (entity == null) {
            return null;
        }
        Model model = (Model) entity;
        Set<Map.Entry<String, Object>> entrySet = model._getAttrsEntrySet();
        if (entrySet.size() > 0) {
            entrySet.forEach(entry -> {
                String attrName = entry.getKey();
                // 由 underline 转为 camelcase
                String fieldName = StrUtil.toCamelCase(attrName);
                Object entryValue = entry.getValue();
                try {
                    ReflectUtil.setFieldValue(entity, fieldName, entryValue);
                } catch (IllegalArgumentException e) {
//                    log.error("[sql-orm] attr [{}] to field [{}] error: {}", attrName, fieldName, e.getLocalizedMessage());
                    // 处理时间等字段
                    Field field = ReflectUtil.getField(tblClass, fieldName);
                    Class<?> fieldType = field.getType();
                    if (entryValue instanceof Timestamp) {
                        Timestamp timestamp = (Timestamp) entryValue;
                        if (fieldType.isAssignableFrom(LocalDate.class)) {
                            ReflectUtil.setFieldValue(entity, fieldName, timestamp.toLocalDateTime().toLocalDate());
                        } else if (fieldType.isAssignableFrom(LocalDateTime.class)) {
                            ReflectUtil.setFieldValue(entity, fieldName, timestamp.toLocalDateTime());
                        } else if (fieldType.isAssignableFrom(Date.class)) {
                            ReflectUtil.setFieldValue(entity, fieldName, new Date(timestamp.getTime()));
                        } else if (long.class.equals(fieldType) || Long.class.equals(fieldType)) {
                            ReflectUtil.setFieldValue(entity, fieldName, timestamp.getTime());
                        }
                    }

                }
            });
        }

        return entity;
    }
}
